<template>
  <div style="padding: 0 17px">
    <Breadcrumb/>
    <div style="display: flex;margin-top: 10px;padding: 10px;">
      <el-button type="primary" style="color: #fff;font-size: 12px;background-color: #1890ff;margin-left: -10px;margin-right: 10px" @click="addItem">添加部件</el-button>
      <span style="min-width: 200px;margin-right: 15px">
          <OrganizationTree
                  @change="load"
                  @tree-select-changed="treeSelectChanged"
                  v-model="searchOrganizationId"
          />
        </span>
      <el-input v-model="searchClientName" placeholder="单位名称"
                style="width: 180px;height: 33px;margin-right: 15px;font-size: 13px;" clearable></el-input>
      <el-input v-model="searchEquipmentId" placeholder="设备识别码"
                style="width: 180px;height: 33px;margin-right: 15px;font-size: 13px;" clearable></el-input>
      <el-input v-model="searchEquipmentName" placeholder="设备名称"
                style="width: 180px;height: 33px;margin-right: 15px;font-size: 13px;" clearable></el-input>
      <el-input v-model="searchName" placeholder="部件名称"
                style="width: 180px;height: 33px;margin-right: 15px;font-size: 13px;" clearable></el-input>
      <el-input v-model="searchModel" placeholder="部件型号"
                style="width: 180px;height: 33px;margin-right: 15px;font-size: 13px;" clearable></el-input>
      <el-select style="width: 190px;margin-right: 15px" v-model="searchUnitType" placeholder="选择部件类型" clearable>
        <el-option
                v-for="item in typeOptions"
                :key="item.id"
                :label="item.typeName"
                :value="item.id">
        </el-option>
      </el-select>
      <el-input v-model="searchAddress" placeholder="安装位置"
                style="width: 180px;height: 33px;margin-right: 15px;font-size: 13px;" clearable></el-input>
      <el-button type="primary" style="color: #fff;font-size: 12px;background-color: #1890ff" @click="load">搜索
      </el-button>
      <el-button type="success" style="" @click="importData">导入</el-button>
      <el-button type="success" style="" @click="exportData">导出</el-button>
      <!--<el-upload-->
              <!--:before-upload="checkFileType"-->
              <!--class="avatar-uploader"-->
              <!--:action="'/api/files/upload'"-->
              <!--:on-success="photoHandleSuccess"-->
              <!--:show-file-list="false"-->
      <!--&gt;-->
        <!--<img width="100" height="100" v-if="form.bgUrl" :src="form.bgUrl" class="avatar">-->
        <!--<img width="100" height="100" v-else>-->
        <!--<button v-if="form.bgUrl" class="delete-btn" @click="deleteImage">x</button>-->
      <!--</el-upload>-->
      <!--<el-upload-->
              <!--:action="'/api/files/upload'"-->
              <!--class="avatar-uploader"-->
              <!--:file-list="caseForm.annex"-->
              <!--:on-success="annexUploadSuccess"-->
              <!--:on-remove="annexRemove"-->
              <!--style="width:100%"-->
              <!--drag-->
              <!--multiple-->
      <!--&gt;-->
        <!--<el-icon class="el-icon&#45;&#45;upload">-->
          <!--<upload-filled/>-->
        <!--</el-icon>-->
        <!--<div class="el-upload__text">-->
          <!--拖拽或<em>点击</em>上传-->
        <!--</div>-->
        <!--<div class="el-upload__tip">-->
          <!--(请上传小于10MB的文件)-->
        <!--</div>-->
      <!--</el-upload>-->
    </div>
    <div>
      <el-table :data="tableData" :row-style="{ height: '77px' }" border
                style="width: calc(100vw - 240px);margin-top: 20px;height: 70vh;color: #909399;font-size: 15px;">
        <el-table-column prop="id" label="ID" width="100"/>
        <el-table-column prop="clientName" label="单位名称" width="200"/>
        <el-table-column prop="equipmentId" label="设备识别码" width="auto"/>
        <el-table-column prop="equipmentName" label="设备名称" width="150"/>
        <el-table-column prop="partName" label="部件名称" width="150"/>
        <el-table-column prop="partTypeName" label="部件类型" width="150"/>
        <el-table-column prop="warnStateName" label="部件状态" width="150"/>
        <el-table-column prop="partModel" label="部件型号" width="150"/>
        <el-table-column prop="installSite" label="安装位置" width="150"/>
        <el-table-column prop="partAreaCode" label="部件区号" width="150"/>
        <el-table-column prop="partLoopCode" label="部件回路号" width="150"/>
        <el-table-column prop="partBitCode" label="部件位号" width="150"/>
        <el-table-column  label="操作" align="center" fixed="right" width="200">
          <template v-slot="scope">
            <el-button type="primary" size="small" icon="Edit" @click="editItem(scope.row)">编辑</el-button>
            <el-button v-if="this.userInformation.role === 1" type="danger" size="small" icon="Delete" @click="deleteItem(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :background="true"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog title="部件操作" v-model="operationItemDialog" :close-on-click-modal="false" :show-close="false"
               width="700">
      <el-form label-position="left" label-width="100" :inline="true" :model="form" ref="form" :rules="rules">
        <el-form-item label="单位名称" prop="clientId">
          <el-select style="width: 190px" v-model="form.clientId" filterable placeholder="选择单位名称">
            <el-option
                    v-for="item in clientOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备识别码" prop="equipmentInputStoreId">
          <el-select style="width: 190px" v-model="form.equipmentInputStoreId" filterable placeholder="选择设备识别码">
            <el-option
                    v-for="item in equipmentOptions"
                    :key="item.id"
                    :label="item.equipmentId"
                    :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部件名称" prop="partName">
          <el-input placeholder="部件名称" style="width: 190px;" v-model="form.partName"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="部件类型" prop="partTypeId">
          <el-select style="width: 190px" v-model="form.partTypeId" filterable placeholder="选择部件类型">
            <el-option
                    v-for="item in typeOptions"
                    :key="item.id"
                    :label="item.typeName"
                    :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="安装位置" prop="installSite">
          <el-input placeholder="安装位置" style="width: 190px;" v-model="form.installSite"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="部件型号" prop="partModel">
          <el-input placeholder="部件型号" style="width: 190px;" v-model="form.partModel"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="部件区号" prop="partAreaCode">
          <el-input placeholder="部件区号" style="width: 190px;" v-model="form.partAreaCode"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="部件回路号" prop="partLoopCode">
          <el-input placeholder="部件回路号" style="width: 190px;" v-model="form.partLoopCode"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="部件位号" prop="partBitCode">
          <el-input placeholder="部件位号" style="width: 190px;" v-model="form.partBitCode"
                    autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reset('form')">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="导入" v-model="dialogImportVisible" width="520px">
      <el-form label-position="right" label-width="100px">
        <el-form-item label="模板下载:" padding-top:10px>
          <el-button type="primary" size="small" style="" @click="exportTemplate">设备部件</el-button>
        </el-form-item>
        <el-form-item label="文件" padding-top:-20px>
          <el-upload :headers="headers"
                           :multiple="false"
                     :on-success="onUploadSuccess"
                     :on-error="onUploadError"
                     :action="serverIp+'/equipment-unit/importData'"
                     class="upload-demo">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传xlsx文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImportVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from "@/components/Breadcrumb.vue";
import request from "@/utils/request.js";
import OrganizationTree from "@/components/OrganizationTree.vue";
import {serverIp} from "../../../public/static/config"
export default {
  name: "EquipmentUnit",
  components: {Breadcrumb, OrganizationTree},
  data() {
    return{
      serverIp,
                headers: {
                    token:  JSON.parse(localStorage.getItem('user')).token,
                },
      dialogImportVisible: false,
      userInformation: JSON.parse(localStorage.getItem("user")),
      operationItemDialog: false,  // 弹窗
      addGroupDialog:false,
      searchClientName: '',
      searchEquipmentId: '',
      searchEquipmentName: '',
      searchName: '',
      searchAddress: '',
      searchModel: '',
      searchUnitType: '',
      searchOrganizationId:JSON.parse(localStorage.getItem("user")).organization,
      tableData: [],
      form:{},
      ruleForm:[],
      equipmentOptions:[],
      typeOptions:[],
      selectOptionName: '',
      clientOptions:[],
      videoTypeOptions:[
        {
          value: '0',
          label: '海康'
        }, {
          value: '1',
          label: '萤石'
        }, {
          value: '2',
          label: '大华'
        }
      ],
      currentData:{},
      rules: {
        // clientId: [
        //   {required: true, message: '请选择单位名称', trigger: 'blur'},
        // ],
        // clientName: [
        //   {required: true, message: '请选择单位名称', trigger: 'blur'},
        // ],
      },
      currentPage: 1,
      pageSize: 10,
      total: 10,
      isEdit: false,
      // partAreaCode:'',
      // partLoopCode:'',
      // partBitCode:'',
      // partModel:'',
    }
  },
  created() {
    this.load()
    this.getEquipmentOptions()
    this.getTypeOptions()
    this.getClientOptions()
    // this.combinedParam()
  },
  methods: {
    importData() {
      this.dialogImportVisible = true;
    },
    onUploadSuccess() {
      this.$message.success('上传成功');
      this.dialogImportVisible = false;
      location.reload();
    },
    onUploadError(){
      this.$message.error('上传失败');
    },
    // 模板下载
    exportTemplate() {
      window.location.href = '../xlsx/equipmentUnit.xlsx'
    },
    exportData() {
      let level = JSON.parse(localStorage.getItem("user")).level
      if (this.currentData.level!==undefined){
        level=this.currentData.level
      }
      if (this.clientOrEquiNum===undefined){
        this.clientOrEquiNum=""
      }
      if (this.nameOrNumOrAddr===undefined){
        this.nameOrNumOrAddr=""
      }
      let isAllClient = JSON.parse(localStorage.getItem("user")).isAllClient;
      let clientIds;
      if (isAllClient === "1") {
        clientIds = JSON.parse(localStorage.getItem("user")).clientIds;
      } else {
        clientIds = [];
      }
      window.open(serverIp + '/equipment-unit/export?clientName='+this.searchClientName+
      "&equipmentId="+this.searchEquipmentId+"&equipmentName="+this.searchEquipmentName+"&name="+this.searchName+"&address="+this.searchAddress+"&model="+this.searchModel+"&typeId="+this.searchUnitType+"&level="+level+"&organizationId="+this.searchOrganizationId+"&isAllClient="+isAllClient+"&clientIds="+clientIds);
    },
    // combinedParam() {
    //   return this.partModel = this.partAreaCode + this.partLoopCode + this.partBitCode;
    // },
    getEquipmentOptions(){
      let level = JSON.parse(localStorage.getItem("user")).level
      let organization = JSON.parse(localStorage.getItem("user")).organization
      let isAllClient = JSON.parse(localStorage.getItem("user")).isAllClient;
      let clientIds;
      if (isAllClient === "1") {
        clientIds = JSON.parse(localStorage.getItem("user")).clientIds;
      } else {
        clientIds = [];
      }
      let clientId = this.$store.state.currentClientInfo?.id??""
      request.get("/equipment-input-store/all?level="+level+"&organizationId="+organization+"&isAllClient="+isAllClient+"&clientIds="+clientIds+"&clientId="+clientId).then(res=>{
        this.equipmentOptions=res.data
      })
    },
    getTypeOptions(){
      request.get("/equipment-unit-type/all").then(res=>{
        this.typeOptions=res.data
      })
    },
    getClientOptions(){
      let level = JSON.parse(localStorage.getItem("user")).level
      let organizationId = JSON.parse(localStorage.getItem("user")).organization
      let isAllClient = JSON.parse(localStorage.getItem("user")).isAllClient;
      let clientIds;
      if (isAllClient === "1") {
        clientIds = JSON.parse(localStorage.getItem("user")).clientIds;
      } else {
        clientIds = [];
      }
      request.get("/client/listbyName?name="+this.selectOptionName+"&organizationId="+organizationId+"&level="+level+"&isAllClient="+isAllClient+"&clientIds="+clientIds).then(res=>{
        this.clientOptions=res.data
      })
    },
    load(){
      try {
        let level = JSON.parse(localStorage.getItem("user")).level
        if (this.currentData.level!==undefined){
          level=this.currentData.level
        }
        if (this.clientOrEquiNum===undefined){
          this.clientOrEquiNum=""
        }
        if (this.nameOrNumOrAddr===undefined){
          this.nameOrNumOrAddr=""
        }
        let isAllClient = JSON.parse(localStorage.getItem("user")).isAllClient;
        let clientIds;
        if (isAllClient === "1") {
          clientIds = JSON.parse(localStorage.getItem("user")).clientIds;
        } else {
          clientIds = [];
        }
        request.get("/equipment-unit/page?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize+"&clientName="+this.searchClientName+
        "&equipmentId="+this.searchEquipmentId+"&equipmentName="+this.searchEquipmentName+"&name="+this.searchName+"&address="+this.searchAddress+"&model="+this.searchModel+"&typeId="+this.searchUnitType+"&level="+level+"&organizationId="+this.searchOrganizationId+"&isAllClient="+isAllClient+"&clientIds="+clientIds).then(res => {
          if (res.code === '200') {
            for (let key in res.data) {
              if (key === "record") {
                this.tableData= res.data[key];
              } else if (key === "total") {
                this.total = res.data[key];
              }
            }
          } else {
            this.$message.error("错误" + res.msg)
          }
        })
      } catch (e) {
        this.$message.error(e)
      }
    },
    // 新增
    addItem() {
      this.operationItemDialog = true
    },
    // 编辑
    editItem(scope) {
      this.isEdit = true;
      Object.assign(this.form, scope)
      this.operationItemDialog = true
    },
    // 编辑、新增确定按钮
    submitForm(val) {
      this.form.operatorId = JSON.parse(localStorage.getItem("user")).id
      this.$refs[val].validate((valid) => {
        if (valid) {
          request.post("/equipment-unit/edit", this.form).then(res => {
            if (res.code === '200') {
              this.$message({
                message: "成功",
                type: "success"
              })
              this.load()
              if (!this.isEdit) {
                this.clearConditions()
              }
              this.reset(val)
            } else {
              this.$message.error("操作失败" + res.msg)
            }
          })
        }
      })
    },
    // 清空查询条件
    clearConditions() {
      this.selectedState = ""
      this.selectedOrganizationId = JSON.parse(localStorage.getItem("user")).organization;
      this.search = "";
    },
    reset(val) {
      this.isEdit = false;
      this.operationItemDialog = false;
      this.form = {};
      this.$refs[val].clearValidate();
    },
    // 删除确定弹窗
    deleteItem(scope) {
      this.$confirm('是否确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.delete("/equipment-unit/delete/" + scope).then(res => {
          if (res.code === '200') {
            this.$message.success("成功")
            this.load()
          } else {
            this.$message.error(res.msg)
          }
        })
      });
    },
    treeSelectChanged(data, node) {
      this.currentData = data
    },
    handleSizeChange(pageSize) {   // 改变当前每页的个数触发
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {  // 改变当前页码触发
      this.currentPage = pageNum
      this.load()
    },
    // photo上传
    photoHandleSuccess(response) {
      this.form.bgUrl=`/api/file/download${response}`
    },
  }
}
</script>

<style scoped>
:deep(.el-table th .cell) {
  font-weight: 700
}
:deep(.el-form-item__label){
  font-size: 14px;
  font-weight: 700
}
.avatar-uploader{
  position: relative;
  display: inline-block;
}
</style>
